﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;

namespace App50
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            Loaded += (s, e) =>
            {
                this.Storyboard = this.Storyboard ?? new Storyboard { };
                this.SizeChanged += (sender, args) => Setup();
                Setup();
            };
        }

        private void Setup()
        {
            this.Storyboard.Stop();
            this.Storyboard.Children.Clear();
            var width = System.Convert.ToDouble(this.Resources["BackImageWidth"]);
            var height = System.Convert.ToDouble(this.Resources["BackImageHeight"]);
            var scale = (this.ActualHeight / height) * 1.1;

            this.Transform0.ScaleX = this.Transform0.ScaleY = scale;
            TranslateX(scale, this.Transform0, 25000);

            this.Transform1.ScaleX = this.Transform1.ScaleY = scale;
            TranslateX(scale, this.Transform1, 20000);

            this.Transform2.ScaleX = this.Transform2.ScaleY = scale;
            TranslateX(scale, this.Transform2, 15000);

            this.Storyboard.Begin();
        }

        private void TranslateX(double scale, CompositeTransform transform, double duration)
        {
            var width = System.Convert.ToDouble(this.Resources["BackImageWidth"]);
            var animateX = new DoubleAnimation
            {
                To = (-width * scale),
                FillBehavior = Windows.UI.Xaml.Media.Animation.FillBehavior.Stop,
                RepeatBehavior = RepeatBehavior.Forever,
                Duration = TimeSpan.FromMilliseconds(duration)
            };
            this.Storyboard.Children.Add(animateX);
            Storyboard.SetTarget(animateX, transform);
            Storyboard.SetTargetProperty(animateX, "TranslateX");
        }

        public DispatcherTimer Timer { get; set; }
        public Storyboard Storyboard { get; set; }
    }
}
